package cn.gson.school.controller.caiwu;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.school.dao.caiwu.FuPinApplyDao;
import cn.gson.school.dao.caiwu.FuPinDao;
import cn.gson.school.dao.jiaoxue.ClassDao;
import cn.gson.school.dao.jiaoxue.StudentDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.entity.caiwu.FuPinApplyEntity;
import cn.gson.school.entity.caiwu.FuPinEntity;
import cn.gson.school.entity.jiaoxue.ClassEntity;
import cn.gson.school.entity.jiaoxue.StudentEntity;
import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.mappers.caiwu.FuPinMapper;
import cn.gson.school.service.ImagesService;

@Controller
@RequestMapping("/cw-fupin-list")
public class FuPinController {

	@Autowired
	private FuPinMapper fupinmapper;
	// 扶贫
	@Autowired
	private FuPinDao fupindao;
	// 扶贫详情
	@Autowired
	private FuPinApplyDao fupinapplyDao;
	// 学生
	@Autowired
	private StudentDao studentDao;
	// 班级
	@Autowired
	private ClassDao classDao;
	// 教员
	@Autowired
	private UserDao userDao;

	@Autowired
	private UserInfoDao userinfoDao;
	//图片
	@Autowired
	private ImagesService imgService;
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(FuPinEntity fupin, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<FuPinEntity> pageData = fupinmapper.fupinlist(fupin);
		PageInfo<FuPinEntity> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	/**
	 * 获取表单
	 */
	@GetMapping({ "cw-add-fupin", "cw-add-fupin/{id}" })
	public String fupin(@PathVariable(name = "id", required = false) Long id, Model model) {

		if (id != null) {
			FuPinEntity fupin = fupindao.findOne(id);
			model.addAttribute("FuPinEntity", fupin);

			// 获取班级id
			ClassEntity csentity = fupin.getClassId();
			model.addAttribute("classEntity", csentity);
			// 获取学生id
			StudentEntity stentity = fupin.getStudentinfo();
			model.addAttribute("studentEntity", stentity);
			//获取用户
			UserInfoEntity userEntity = fupin.getUserinfoId();
			model.addAttribute("UserInfoEntity", userEntity);
		}
		// 班级
		Iterable<ClassEntity> list = classDao.findByDelete(1);
		model.addAttribute("classList", list);
		// 学生
		Iterable<StudentEntity> student = studentDao.findAll();
		model.addAttribute("studentList", student);
		//用户
		Iterable<UserInfoEntity> userlist = userinfoDao.findAll();
		model.addAttribute("UserInfolist", userlist);

		return "caiwu/cw-add-fupin";
	}

	/**
	 * 编辑
	 * 
	 * @throws ParseException
	 */
	@SuppressWarnings("unlikely-arg-type")
	@PostMapping("/save")
	@ResponseBody
	@Transactional
	public Map<String, Object> save(HttpSession session,@Valid FuPinEntity fuPinEntity, HttpServletRequest request, Model model,
			@SessionAttribute("user") UserEntity user,@RequestParam("file")MultipartFile file,BindingResult br) throws ParseException {
		Map<String, Object> obj = new HashMap<String, Object>();
		//获取用户
		UserInfoEntity userInfoEntity =	(UserInfoEntity) session.getAttribute("userinfo");
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldError());
		} else {
			// 获取表单值
			String fupinid = request.getParameter("fupinid");// 扶贫id
			String studentName = request.getParameter("studentName");// 扶贫人姓名、外键
			StudentEntity studentEntity = studentDao.findOne(Long.valueOf(studentName));// 学生名称
			String className = request.getParameter("className");// 班级名称、外键
			ClassEntity classEntity = classDao.findOne(Long.valueOf(className));
			String fuPinData = request.getParameter("fuPinData");// 扶贫资料
			String fuPinProve = request.getParameter("fuPinProve");// 扶贫证明
			String applyTime = request.getParameter("applyTime");// 申请时间、外键
			String state = request.getParameter("state");// 状态
			String fuPinReason = request.getParameter("fuPinReason");// 扶贫原因

			// 实体类
			FuPinEntity pinEntity;
			FuPinApplyEntity fPApplyEntity;
			// 判断是否是添加
			if (fupinid == null || "".equals(fupinid)) {
				pinEntity = new FuPinEntity();
				fPApplyEntity = new FuPinApplyEntity();
				fPApplyEntity.setApplyTime(new Date());
			} else {
				pinEntity = fupindao.findOne(Long.valueOf(fupinid));
				pinEntity.setFuPinId(Long.valueOf(fupinid));
				fPApplyEntity = fupinapplyDao.findOne(pinEntity.getFuPinApplyId().getFupinApplyId());
			}

			// 添加主键
			pinEntity.setFuPinData(fuPinData);// 扶贫资料
			pinEntity.setFuPinProve(fuPinProve);// 扶贫证明
			pinEntity.setFuPinState(state);// 状态
			pinEntity.setFuPinReason(fuPinReason);// 扶贫原因

			// 添加外键
			pinEntity.setStudentinfo(studentEntity);// 学生名称
			pinEntity.setClassId(classEntity);// 班级名称
			pinEntity.setUserinfoId(userInfoEntity);// 操作人
			pinEntity.setFuPinApplyId(fPApplyEntity);// 扶贫详情
			// 扶贫详情外键
			
			// 判断是否为时间格式--
			String path = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";// 定义匹配规则
			Pattern p = Pattern.compile(path);// 实例化Pattern
			Matcher m = p.matcher(applyTime);// 验证字符串内容是否合法
			if (m.matches()) { // 使用正则验证
				System.out.println("输入的日期格式合法！");
				fPApplyEntity.setApplyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(applyTime));// 发布时间
			} else {
				obj.put("message", "收款时间输入有误啊！");
				return obj;
			} 
			//文件上传
			ImageEntity img = null;
			try {
				img = imgService.upload(user, "sign", file,"");
			} catch (Exception e) {
				obj.put("上传失败！", e);
			}
			if(img != null && !"".equals(img)) {
				pinEntity.setImagesId(img);
			}else {
				obj.put("message", "请选择图片");
				return obj;
			}
			
			
			fPApplyEntity.setUserinfo(userInfoEntity);// 操作人
			fPApplyEntity.setStudentinfoId(studentEntity);// 学生

			fupindao.save(pinEntity);
			fupinapplyDao.save(fPApplyEntity);
			System.out.println("操作成功！");
			obj.put("success", true);
		}
		return obj;
	}
}
